
package com.pos.app.util.db.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;

import com.pos.app.util.db.DBException;
import com.pos.app.util.db.entity.MyPKProperyEntity;
import com.pos.app.util.db.entity.MyPropertyEntity;
import com.pos.app.util.db.entity.MyTableInfoEntity;

/**
 * @Description 数据库表工厂类
 */
public class SWTableInfofactory
{
	/**
	 * 表名为键，表信息为值的HashMap
	 */
	private static final HashMap<String, MyTableInfoEntity> tableInfoEntityMap = new HashMap<String, MyTableInfoEntity>();

	private SWTableInfofactory()
	{

	}

	private static SWTableInfofactory instance;

	/**
	 * 获得数据库表工厂
	 * 
	 * @return 数据库表工厂
	 */
	public static SWTableInfofactory getInstance()
	{
		if (instance == null)
		{
			instance = new SWTableInfofactory();
		}
		return instance;
	}

	/**
	 * 获得表信息
	 * 
	 * @param clazz
	 *            实体类型
	 * @return 表信息
	 * @throws DBException
	 */
	public MyTableInfoEntity getTableInfoEntity(Class<?> clazz) throws DBException
	{
		if (clazz == null)
			throw new DBException("表信息获取失败，应为class为null");
		MyTableInfoEntity tableInfoEntity = tableInfoEntityMap.get(clazz.getName());
		if (tableInfoEntity == null)
		{
			tableInfoEntity = new MyTableInfoEntity();
			tableInfoEntity.setTableName(SWDBUtils.getTableName(clazz));
			tableInfoEntity.setClassName(clazz.getName());
			Field idField = SWDBUtils.getPrimaryKeyField(clazz);
			if (idField != null)
			{
				MyPKProperyEntity pkProperyEntity = new MyPKProperyEntity();
				pkProperyEntity.setColumnName(SWDBUtils.getColumnByField(idField));
				pkProperyEntity.setName(idField.getName());
				pkProperyEntity.setType(idField.getType());
				pkProperyEntity.setAutoIncrement(SWDBUtils.isAutoIncrement(idField));
				tableInfoEntity.setPkProperyEntity(pkProperyEntity);
			}
			else
			{
				tableInfoEntity.setPkProperyEntity(null);
			}
			List<MyPropertyEntity> propertyList = SWDBUtils.getPropertyList(clazz);
			if (propertyList != null)
			{
				tableInfoEntity.setPropertieArrayList(propertyList);
			}

			tableInfoEntityMap.put(clazz.getName(), tableInfoEntity);
		}
		if (tableInfoEntity == null || tableInfoEntity.getPropertieArrayList() == null || tableInfoEntity.getPropertieArrayList().size() == 0)
		{
			throw new DBException("不能创建+" + clazz + "的表信息");
		}
		return tableInfoEntity;
	}
}
